package org.lab.tracecash.io;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.flatpack.DataSet;
import net.sf.flatpack.DefaultParserFactory;
import net.sf.flatpack.Parser;

import org.lab.tracecash.model.Account;
import org.lab.tracecash.model.Transaction;

public abstract class BaseCsvImporter implements TransactionImporter {

	protected abstract SimpleDateFormat getDateFormat();

	protected abstract String getColumnValueDate();

	protected abstract String getColumnAmount();

	protected abstract String getColumnDesc();

	protected abstract String getLongDesc(DataSet ds);

	@Override
	public List<Transaction> parse(Account defaultSource, Account defaultTarget, InputStream inputStream) {
		try {
			Parser parser = DefaultParserFactory.getInstance().newDelimitedParser(new InputStreamReader(inputStream, "UTF8"), ',', '"');
			DataSet ds = parser.parse();
			ds.next();
			List<Transaction> result = new ArrayList<Transaction>();
			while (ds.next()) {
				try {
					Date valueDate = ds.getDate(getColumnValueDate(), new SimpleDateFormat("yyyy/MM/dd"));
					BigDecimal amount = new BigDecimal(ds.getString(getColumnAmount()));
					String desc = ds.getString(getColumnDesc());
					String longDesc = getLongDesc(ds);
					Transaction i = new Transaction();
					i.setAmount(amount);
					i.setDesc(desc);
					i.setFrom(defaultSource);
					i.setTo(defaultTarget);
					i.setLongDesc(longDesc);
					i.setValueDate(valueDate);
					result.add(i);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
			return result;

		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

}
